use image::imageops::FilterType;
use image::{GenericImage, GenericImageView, ImageBuffer, RgbImage};
use std::fs::{self, DirEntry};
use std::io;
use std::path::Path;

use log::{debug, error, info, warn};
use log4rs;

mod settings;
use settings::Settings;

fn main() {
    log4rs::init_file("logging.yaml", Default::default()).unwrap();
    info!("开始执行转换");
    // 获取配置参数
    let s = Settings::new().unwrap();
    // let mut rate: f32 = s.image.rate;
    // let mut hight: u32 = s.image.hight;
    // let mut width: u32 = s.image.width;

    let images_dir = Path::new("images");
    visit(images_dir, cvt, &s).unwrap();
    info!("转换完成")
}

fn visit(file: &Path, cvt: fn(&DirEntry, &Settings), s: &Settings) -> io::Result<()> {
    if file.is_dir() {
        for entry in fs::read_dir(file)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit(&path, cvt, s)?;
            } else {
                cvt(&entry, s);
            }
        }
    }
    Ok(())
}

fn cvt(entry: &DirEntry, s: &Settings) {
    info!("正在转换: {:?}", entry.path());
    let origin = entry.path();
    let converted = Path::new("converted").join(origin.strip_prefix("images").unwrap());
    debug!("converted:{:?}", converted);
    // 创建转换后的目录
    let converted_dir = converted.parent().unwrap();
    debug!("转换后的目录:{:?}", converted_dir);
    fs::create_dir_all(converted_dir).unwrap();
    // 转换
    convert(origin.as_path(), converted.as_path(), s);
}

fn convert(origin: &Path, converted: &Path, s: &Settings) {
    // let image_path = "images/00000001.TIF";

    let img = image::open(origin).unwrap();
    let (mut w, mut h) = img.dimensions();
    let mut rate = 0.24f32;
    if let Some(r) = s.image.rate {
        rate = r;
    }
    w = ((w as f32) * (rate as f32)) as u32;
    h = ((h as f32) * (rate as f32)) as u32;
    if let Some(hight) = s.image.hight {
        h = hight;
    }
    if let Some(width) = s.image.width {
        w = width;
    }

    // println!("hight: {}, width: {}", h, w);
    let img = img.resize(w, h, FilterType::Nearest);
    // img.save("images/00000001.output.TIF").unwrap();
    img.save(converted).unwrap();
}
